package commons.base.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.spi.SelectorProvider;

public class NioServer implements AutoCloseable{

	private AcceptWorkerGroup acceptWorkerGroup;
	private IOWorkerGroup ioWorkerGroup;
	
	public NioServer() throws IOException{
		SelectorProvider selectorProvider = SelectorProvider.provider();
		
		ioWorkerGroup = new IOWorkerGroup(selectorProvider);
		acceptWorkerGroup = new AcceptWorkerGroup(selectorProvider, ioWorkerGroup);
	}
	
	public void bind(InetSocketAddress socketAddress) throws IOException{
		acceptWorkerGroup.chooseWorker().bind(socketAddress);
	}
	
	@Override
	public void close() throws Exception {
		if(acceptWorkerGroup != null){
			try {
				acceptWorkerGroup.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if(ioWorkerGroup != null){
			try {
				ioWorkerGroup.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
